<template>
  <el-form label-width="100px">
    <el-form-item label="Sku名称">
      <el-input v-model="skuFormData.skuName" placeholder="SKU名称"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)">
      <el-input
        v-model="skuFormData.price"
        type="number"
        placeholder="价格(元)"
      ></el-input>
    </el-form-item>
    <el-form-item label="重量(g)">
      <el-input
        v-model="skuFormData.weight"
        type="number"
        placeholder="重量(g)"
      ></el-input>
    </el-form-item>
    <el-form-item label="Sku描述(元)">
      <el-input
        v-model="skuFormData.skuDesc"
        type="textarea"
        placeholder="SKU描述"
      ></el-input>
    </el-form-item>
    <el-form-item label="平台属性">
      <el-form :inline="true" label-width="100px">
        <el-form-item
          :label="item.attrName"
          v-for="(item) in hasAttr"
          :key="item.id"
        >
          <el-select
            v-model="item.attrIdAndValueId"
            placeholder="请选择"
            style="width: 220px"
          >
            <el-option
              v-for="item2 in item.attrValueList"
              :key="item2.id"
              :label="item2.valueName"
              :value="`${item.id}:${item2.id}`"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-form :inline="true" label-width="100px">
        <el-form-item
          :label="item.saleAttrName"
          v-for="item in saleAttrArr"
          :key="item.id"
        >
          <el-select
            v-model="item.saleAttrIdAndValueId"
            placeholder="请选择"
            style="width: 220px"
          >
            <el-option
              v-for="item2 in item.spuSaleAttrValueList"
              :key="item2.id"
              :label="item2.saleAttrValueName"
              :value="`${item.id}:${item2.id}`"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="图片名称">
      <el-table ref="tableRef" :data="imgArr" border>
        <el-table-column type="selection" align="center" width="80px"> </el-table-column>
        <el-table-column label="图片">
          <template #="{ row }">
            <img :src="row.imgUrl" alt="暂无图片" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column prop="imgName" label="名称"> </el-table-column>
        <el-table-column label="操作">
          <template #="{ row }">
            <el-button type="primary" @click="setDefaultImg(row)">设为默认</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="addSkuInfo">保存</el-button>
      <el-button type="default" @click="$emit('updateContentShow', 0)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { reqAddSku, reqSpuImageList, reqSpuSaleAttr } from "@/api/product/spu";
import { reqHasAttr } from "@/api/product/attr";
import {
  SpuImgObj,
  SpuSaleAttrObj,
  SpuImgResData,
  SpuSaleAttrResData,
  SkuAddObj,
  SpuObj,
} from "@/api/product/spu/types";
import type { AttrObj, AttrResData } from "@/api/product/attr/types";
import { ElMessage } from "element-plus";
const $emit = defineEmits(["updateContentShow"]);
// 表格实例
const tableRef = ref();
// SKU表单数据
const skuFormData = ref<SkuAddObj>({
  category3Id: "", // 三级分类Id
  spuId: "",
  tmId: "",
  // v-model收集
  skuName: "",
  price: "",
  weight: "",
  skuDesc: "",
  // 保存时收集
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
  skuDefaultImg: "",
});
// 平台属性数据
const hasAttr = ref<AttrObj[]>([]);
// 照片墙数据
const imgArr = ref<SpuImgObj[]>([]);
// 销售属性数据
const saleAttrArr = ref<SpuSaleAttrObj[]>([]);
// 添加Sku时初始化数据
const addSkuInitData = async (
  spuData: SpuObj,
  c1Id: number,
  c2Id: number,
  c3Id: number
) => {
  // 先清空数据
  skuFormData.value = {
    category3Id: "", // 三级分类Id
    spuId: "",
    tmId: "",
    // v-model收集
    skuName: "",
    price: "",
    weight: "",
    skuDesc: "",
    // 保存时收集
    skuAttrValueList: [],
    skuSaleAttrValueList: [],
    skuDefaultImg: "",
  };
  hasAttr.value = [];
  imgArr.value = [];
  saleAttrArr.value = [];
  // skuFormData部分数据收集
  skuFormData.value.category3Id = c3Id;
  skuFormData.value.spuId = spuData.id as number;
  skuFormData.value.tmId = spuData.tmId as number;
  // 获取平台属性数据
  let result: AttrResData = await reqHasAttr(c1Id, c2Id, c3Id);
  if (result?.code === 200) {
    hasAttr.value = result?.data;
  }
  // 获取照片墙数据
  let result2: SpuImgResData = await reqSpuImageList(spuData.id as number);
  if (result2?.code === 200) {
    imgArr.value = result2?.data;
  }
  // 获取销售属性数据
  let result3: SpuSaleAttrResData = await reqSpuSaleAttr(spuData.id as number);
  if (result3?.code === 200) {
    saleAttrArr.value = result3?.data;
  }
};
// 将方法暴露出去，供父组件调用
defineExpose({
  addSkuInitData,
});
// 设为默认按钮的回调
const setDefaultImg = (row: SpuImgObj) => {
  // 1、先取消所有行的勾选（el-table自带的方法）
  tableRef.value.clearSelection();
  // 2、将点击行的复选框勾上（el-table自带的方法）
  tableRef.value.toggleRowSelection(row, true);
  // 收集默认图片的地址
  skuFormData.value.skuDefaultImg = row.imgUrl as string;
};
// 保存按钮的回调
const addSkuInfo = async () => {
  // 收集平台属性数据（此处不能使用map，因为对象不一定都有attrIdAndValueId，若没有，则没有返回值，为undefined，类型校验不通过）
  skuFormData.value.skuAttrValueList = hasAttr.value.reduce((pre: any, next: any) => {
    if (next.attrIdAndValueId) {
      const [attrId, valueId] = next.attrIdAndValueId.split(":");
      pre.push({ attrId, valueId });
    }
    return pre;
  }, []);
  // 收集销售属性数据
  skuFormData.value.skuSaleAttrValueList = saleAttrArr.value.reduce(
    (pre: any, next: any) => {
      if (next.saleAttrIdAndValueId) {
        const [saleAttrId, saleAttrValueId] = next.saleAttrIdAndValueId.split(":");
        pre.push({ saleAttrId, saleAttrValueId });
      }
      return pre;
    },
    []
  );
  // 发送请求，保存Sku
  let result: any = await reqAddSku(skuFormData.value);
  if (result?.code === 200) {
    ElMessage.success("SKU添加成功");
    $emit("updateContentShow", 0);
  } else {
    ElMessage.error("SKU添加失败");
    $emit("updateContentShow", 0);
  }
};
</script>

<style scoped lang="scss">
.el-form {
  .el-form-item {
    &:last-child {
      margin-bottom: 0px;
    }
  }
}
</style>
